use minimp3_fixed::{Decoder, Error, Frame};
use tokio::fs::File;
use tokio::sync::mpsc::Sender;


pub(crate) async fn play_mp3(path: &str, config: &cpal::StreamConfig, tx:Sender<Vec<f32>>) -> Result<(), anyhow::Error> {
    let file = File::open(path).await?;
    let mut decoder = Decoder::new(file);
    loop {
        match decoder.next_frame_future().await {
            Ok(frame) => {
                let samples: Vec<f32> = convert_to_device_format(&frame, &config);
                tx.send(samples).await.unwrap();
            }
            Err(Error::Eof) => break,
            Err(e) => println!("err: {:?}", e),
        }
    }
    Ok(())
}


// 将 MP3 帧转换为设备支持的格式
pub(crate) fn convert_to_device_format(frame: &Frame, config: &cpal::StreamConfig) -> Vec<f32> {
    // 1. 处理声道数转换（如 MP3 是单声道，设备需要立体声）
    let interleaved = match (frame.channels as usize, config.channels as usize) {
        (1, 2) => {
            // 单声道 → 立体声：复制左声道到右声道
            frame
                .data
                .iter()
                .flat_map(|&s| [s as f32 / 32768.0, s as f32 / 32768.0])
                .collect()
        }
        (2, 1) => {
            // 立体声 → 单声道：取左右声道平均值
            frame
                .data
                .chunks(2)
                .map(|chunk| ((chunk[0] + chunk[1]) as f32) / (2.0 * 32768.0))
                .collect()
        }
        (n, m) if n == m => {
            // 声道数相同，直接转换格式
            frame.data.iter().map(|&s| s as f32 / 32768.0).collect()
        }
        _ => panic!("不支持的声道转换: {} → {}", frame.channels, config.channels),
    };

    // 2. 采样率转换（简化版：实际应使用专业库如 rubato）
    if frame.sample_rate != config.sample_rate.0 as i32 {
        eprintln!(
            "警告: 采样率不匹配 (MP3: {}Hz, 设备: {}Hz)，可能导致声音异常",
            frame.sample_rate, config.sample_rate.0
        );
        // 此处应添加采样率转换逻辑
    }

    interleaved
}
